﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.Phone.ViewModel

Namespace Pages

    Partial Public Class LoginPage
        Inherits PhoneApplicationPage

        Public Sub New()
            Me.InitializeComponent()

            Me.PageTransitionReset.Begin()
        End Sub

        Public Property ViewModel() As LoginPageViewModel
            Get
                Return TryCast(Me.DataContext, LoginPageViewModel)
            End Get
            Set(ByVal value As LoginPageViewModel)
                Me.DataContext = value
            End Set
        End Property

        Protected Overrides Sub OnNavigatedTo(ByVal e As NavigationEventArgs)
            If Not GetApplicationState(Of Boolean)("UserBackPress") Then
                ' If there is a valid authentication token available in the isolated storage,
                ' then the application navigates to the main pivot page and is registered with 
                ' the push notification service in case 'push notification' is enabled by the user.
                ' If there is not any valid authentication token available in the isolated storage,
                ' then the application navigates to the log in page.
                App.CloudClientFactory.VerifyLoggedIn(Function() Me.NavigationService.Navigate(New Uri("/Pages/MainPage.xaml", UriKind.Relative)), Sub() Me.StartTransition())
            Else
                Me.StartTransition()

                SetApplicationState("UserBackPress", False)
            End If
        End Sub

		Protected Overrides Sub OnNavigatedFrom(ByVal e As NavigationEventArgs)
            Me.PageTransitionReset.Begin()
        End Sub

        Private Shared Function GetApplicationState(Of T)(ByVal key As String) As T
            If Not PhoneApplicationService.Current.State.ContainsKey(key) Then
                Return Nothing
            End If

            Return CType(PhoneApplicationService.Current.State(key), T)
        End Function

        Private Shared Sub SetApplicationState(ByVal key As String, ByVal value As Object)
            If PhoneApplicationService.Current.State.ContainsKey(key) Then
                PhoneApplicationService.Current.State.Remove(key)
            End If

            PhoneApplicationService.Current.State.Add(key, value)
        End Sub

        Private Sub StartTransition()
            Me.PageTransitionIn.Begin()
            If Me.ViewModel Is Nothing Then
                Me.ViewModel = New LoginPageViewModel()
            End If

            Me.ViewModel.UserName = If(App.CloudClientFactory.UserName, Me.ViewModel.UserName)
            Me.ViewModel.Password = String.Empty
        End Sub

        Private Sub OnLoginButtonClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
            If Me.ViewModel.IsLoginEnabled Then
			    'When the user navigates to an identity provider, the previous login information is cleaned up.
                App.CloudClientFactory.CleanAuthenticationToken()

                Me.ViewModel.Login(
                    Sub()
                        ' Save the username of the last user logged in.
                        App.CloudClientFactory.SetUserName(Me.ViewModel.UserName, Me.ViewModel.RememberMe)

                        Me.NavigationService.Navigate(New Uri("/Pages/MainPage.xaml", UriKind.Relative))
                    End Sub, Sub(msg) MessageBox.Show(msg, "Log in Error", MessageBoxButton.OK))
            Else
                MessageBox.Show("Please fill out all the information in the log in page.", "Log in incomplete", MessageBoxButton.OK)
            End If
        End Sub

        Private Sub OnTextBoxKeyUp(ByVal sender As Object, ByVal e As KeyEventArgs)
            If e.Key = Key.Enter Then
                If sender Is Me.UserNameTextBox Then
                    Me.PasswordBox.Focus()
                Else
                    Me.LoginButton.Focus()
                End If
            End If
        End Sub

        Private Sub OnRegisterButtonClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.NavigationService.Navigate(New Uri("/Pages/RegisterPage.xaml", UriKind.Relative))
        End Sub
    End Class
End Namespace